package com.frxuexi.mynews.viewmodel

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.frxuexi.mynews.intent.VideoIntent
import com.frxuexi.mynews.repository.VideoRepository
import com.frxuexi.mynews.state.VideoState
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.flow.consumeAsFlow
import kotlinx.coroutines.launch

class VideoViewModel:ViewModel() {

    val videoRepo by lazy { VideoRepository() }

    var videoChannel=Channel<VideoIntent>(Channel.UNLIMITED)

    private var _videoState=MutableStateFlow<VideoState>(VideoState.onLoading)
    val videoState:StateFlow<VideoState>
        get() = _videoState

    init {
        handlerIntent()
    }

    private fun handlerIntent() {
        viewModelScope.launch {
            videoChannel.consumeAsFlow().collect{
                when(it){
                    is VideoIntent.getVideos->
                        getVideos(it.page)

                }
            }
        }
    }

    private fun getVideos(page: Int) {
        viewModelScope.launch {
            videoRepo.getVideos(page)
                .collect{
                    if(it.code==0){
                        _videoState.value=VideoState.onVideoSuccess(it.data.records)
                    }else{
                        _videoState.value=VideoState.onError(it.msg)
                    }
                }
        }
    }
}